package com.cai.xiaobai.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cai.xiaobai.entity.UserInfo;
import com.cai.xiaobai.entity.VO.userInfo.LoginVO;
import com.cai.xiaobai.mapper.UserInfoMapper;
import com.cai.xiaobai.result.R;
import com.cai.xiaobai.result.Result;
import com.cai.xiaobai.result.ResultCode;
import com.cai.xiaobai.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cai.xiaobai.utils.RedisTool;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

import static com.cai.xiaobai.utils.TokenUtil.genAccessToken;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-05-13
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    @Resource
    RedisTool redisTool;
    @Override
    public Result getSessionId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={js_code}&grant_type=authorization_code";
        url = url.replace("{appid}", appid).replace("{secret}", secret).replace("{js_code}", code);
        String res = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String  sessionKey = (String) jsonObject.get("session_key");
        String openId = (String) jsonObject.get("openid");
        UserInfo one = this.getOne(new QueryWrapper<UserInfo>().lambda()
            .eq(UserInfo::getOpenId, openId));
        LoginVO loginVO = new LoginVO();
        loginVO.setSessionKey(sessionKey);
//        创建token
        String token = genAccessToken(openId);
        loginVO.setToken(token);
        if (Objects.isNull(one)) {
//            说明没有登录过的
            UserInfo userInfo = new UserInfo();
            userInfo.setOpenId(openId);
            userInfo.setCreateTime(LocalDateTime.now());
            if (!this.save(userInfo)) {
                return R.Fail(ResultCode.INTERNAL_SERVER_ERROR,"注册失败请重试");
            }
            loginVO.setUserInfo(userInfo);
        }else {
            loginVO.setUserInfo(one);
        }
        redisTool.setCacheObject(openId, token);
        return R.Success(loginVO);
    }
}
